﻿using System;
using System.Windows.Forms;

namespace UtilZ.Dotnet.WindowsDesktopEx.Winform
{
    /// <summary>
    /// Winform辅助类
    /// </summary>
    public static class WinformHelper
    {
        /// <summary>
        /// 查找控件指定类型的父窗口
        /// </summary>
        /// <param name="control">目标控件</param>
        /// <param name="targetFormType">父窗口类型,不为null时查找与该类型匹配的父窗口;为null时找到第一级为结果</param>
        /// <returns>查找结果</returns>
        public static Form FindParentForm(this Control control, Type targetFormType = null)
        {
            Form parentForm = null;

            while (control != null)
            {
                if (control is Form)
                {
                    if (targetFormType == null)
                    {
                        parentForm = (Form)control;
                        break;
                    }
                    else
                    {
                        if (control.GetType() == targetFormType)
                        {
                            parentForm = (Form)control;
                            break;
                        }
                    }
                }

                control = control.Parent;
            }

            return parentForm;
        }


        /// <summary>
        /// 判断鼠标是否在控件坐标范围内,在控件内返回true,不在控件内返回false
        /// </summary>
        /// <param name="control">用于判断的控件</param>
        /// <returns>在控件内返回true,不在控件内返回false</returns>
        public static bool MouseInControl(this Control control)
        {
            try
            {
                return control.ClientRectangle.Contains(control.PointToClient(Control.MousePosition));
            }
            catch (ObjectDisposedException)
            {
                return false;
            }
        }

    }
}
